package com.agricultural.security;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 安全管理器（单例模式）
public class SecurityManager {
    private static SecurityManager instance;
    private User currentUser;
    private Map<String, User> users = new HashMap<>();
    private Map<String, List<String>> rolePermissions = new HashMap<>();

    private SecurityManager() {
        // 初始化用户
        users.put("admin", new User("admin", "admin123", UserRole.ADMIN.name()));
        users.put("operator", new User("operator", "operator123", UserRole.OPERATOR.name()));
        users.put("viewer", new User("viewer", "viewer123", UserRole.VIEWER.name()));

        // 初始化角色权限
        initRolePermissions();
    }

    public static synchronized SecurityManager getInstance() {
        if (instance == null) {
            instance = new SecurityManager();
        }
        return instance;
    }

    private void initRolePermissions() {
        // ADMIN权限
        List<String> adminPermissions = new ArrayList<>();
        adminPermissions.add("ADMIN");
        adminPermissions.add("OPERATOR");
        adminPermissions.add("VIEWER");
        rolePermissions.put(UserRole.ADMIN.name(), adminPermissions);

        // OPERATOR权限
        List<String> operatorPermissions = new ArrayList<>();
        operatorPermissions.add("OPERATOR");
        operatorPermissions.add("VIEWER");
        rolePermissions.put(UserRole.OPERATOR.name(), operatorPermissions);

        // VIEWER权限
        List<String> viewerPermissions = new ArrayList<>();
        viewerPermissions.add("VIEWER");
        rolePermissions.put(UserRole.VIEWER.name(), viewerPermissions);
    }

    public boolean login(String username, String password) {
        User user = users.get(username);
        if (user != null && user.verifyPassword(password)) {
            currentUser = user;
            System.out.println("用户 " + username + " 登录成功，角色: " + user.getRole());
            return true;
        }
        System.out.println("登录失败，用户名或密码错误");
        return false;
    }

    public void logout() {
        if (currentUser != null) {
            System.out.println("用户 " + currentUser.getUsername() + " 已登出");
            currentUser = null;
        }
    }

    public boolean hasPermission(String requiredRole) {
        if (currentUser == null) {
            System.out.println("请先登录");
            return false;
        }

        List<String> permissions = rolePermissions.get(currentUser.getRole());
        if (permissions != null && permissions.contains(requiredRole)) {
            return true;
        }

        System.out.println("权限不足，需要 " + requiredRole + " 角色");
        return false;
    }

    public User getCurrentUser() {
        return currentUser;
    }
}